<?php
/**
 * Created by PhpStorm.
 * User: lichuang
 * Date: 2022/9/21
 * Function: 控制器基类
 */

namespace app\controllers;

use Yii;
use app\server\Server;
use app\server\Api;
use app\server\Auth;
use yii\web\Controller;
use app\logic\BaseLogic;

class BaseController extends Controller
{
    public $tokenData = [];
    public $baseLogic = null;

    public function init()
    {
        parent::init();
        if ($this->baseLogic == null) {
            $this->baseLogic = new BaseLogic();
        }

        // 请求日志
        $request = Yii::$app->request;
        if ($request->isPost || $request->isGet) {
            $method = $request->isPost ? 'POST' : 'GET';
            $this->baseLogic->httpLog($method);
        }

        // 签名验证
        # $this->baseLogic->checkSign();

        // 免登陆路由验证
        $REQUEST_URI = Yii::$app->request->getPathInfo();
        $toUrl = trim($REQUEST_URI, "/");
        if (!empty($toUrl)) {

            // 获取配置项
            $systemInfo = Server::getSystem();
            $coreInfo = isset($systemInfo['core']) ? $systemInfo['core'] : [];
            // 免登陆路由列表
            $noToken = isset($coreInfo['no_token']) ? $coreInfo['no_token'] : [];
            // 当前请求地址是否可以免登陆
            foreach ($noToken as $key => $val) {
                // 如果可以免登陆,判断是否存在token,存在则验证(免登陆可以不传token,但如果传了就必须通过验证才行)
                if ($val == $toUrl) {
                    $token = isset($_SERVER['HTTP_TOKEN']) ? $_SERVER['HTTP_TOKEN'] : '';
                    if (!empty($token)) {
                        $tokenData = Auth::deToken($token);
                        if (empty($tokenData)) {
                            Api::error(1000);
                        }
                    } else {
                        return;
                    }
                }
            }
        }

        // TOKEN验证
        $tokenData = $this->baseLogic->tokenCheck();
        if (empty($tokenData)) {
            Api::error(1000);
        } else {
            $this->tokenData = $tokenData;
        }
    }
}